package gw.com.android.ui.gesture_pwd;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.gwtsz.gts2.hx.R;
import com.umeng.analytics.MobclickAgent;

import butterknife.BindView;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.presenter.LoginPresenter;
import gw.com.android.presenter.PresenterImpl;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.gesture_pwd.consts.GesturePwdConst;
import gw.com.android.ui.me.PhoneNumber;
import gw.com.android.utils.MobclickEventUtlis;
import www.com.library.app.AppActivities;
import www.com.library.app.Logger;
import www.com.library.dialog.ToastPopWindow;
import www.com.library.util.CommonUtils;
import www.com.library.util.NetworkMonitor;

public class PasswordCheckActivity extends BaseActivity implements PresenterImpl {


    @BindView(R.id.sign_in_button)
    TextView loginBtn;//登录按钮
    @BindView(R.id.password)
    EditText mPassWordView;
    @BindView(R.id.iv_close)
    ImageView iv_close;
    @BindView(R.id.tv_forget_pwd)
    TextView tv_forget_pwd;

    @Override
    protected int getLayoutView() {
        return R.layout.layout_check_pwd;
    }

    @Override
    protected void initLayoutView() {
        iv_close.setVisibility(View.GONE);
        mPassWordView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String password = mPassWordView.getText().toString();
                if (!TextUtils.isEmpty(password)) {
                    loginBtn.setEnabled(true);
                    loginBtn.setTextColor(getResources().getColor(R.color.color_f));
                    iv_close.setVisibility(View.VISIBLE);
                } else {
                    loginBtn.setEnabled(false);
                    loginBtn.setTextColor(0xFFCFCFCF);
                    iv_close.setVisibility(View.GONE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPassWordView.setText("");
            }
        });
        tv_forget_pwd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ToastPopWindow(PasswordCheckActivity.this, "``TODO``!").show();
            }
        });
    }


    @Override
    protected void initViewData() {
        mPresenter = new LoginPresenter(PasswordCheckActivity.this);
    }

    private LoginPresenter mPresenter;
    private int mSeq = 0;
    private String mCurName;
    private String mPassword;

    /**
     * 尝试 用 用户名登录
     */
    @OnClick(R.id.sign_in_button)
    void accLogin() {
        if (!loginBtn.isEnabled()) {
            return;
        }
        if (CommonUtils.isFastDoubleClick()) {
            return;
        }
        if (!NetworkMonitor.hasNetWork()) {
            return;
        }
        if (mPresenter.isLoading) {
            return;
        }
        mCurName = GTConfig.instance().mCurName;
        mPassword = mPassWordView.getText().toString().trim();
        if (TextUtils.isEmpty(mCurName)) {
            dealException(AppMain.getAppString(R.string.login_account_null));
            return;
        } else if (TextUtils.isEmpty(mPassword)) {
            dealException(AppMain.getAppString(R.string.login_password_null));
            return;
        }
        showLoading();
        PhoneNumber.getInstance().reset();
        GTConfig.instance().isFromLogin = true;
        GTConfig.instance().isSubscribed = false;

        GTConfig.instance().mCurLoginPhone = "";
        GTConfig.instance().isPhoneLogin = false;
        if (mCurName.startsWith(ConfigUtil.instance().mConfigObject.optString(ConfigType.PREFIX_DEMO_ACCOUNT))) {
            Logger.i("用户点击账号登录按钮执行登录功能，demo登录");
            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_DEMO);
            MobclickAgent.onProfileSignIn("Demo_Login", mCurName);
            MobclickEventUtlis.MobclickEvent(this, "Demo_Login");
            executeLogin(mCurName, mPassword);
        } else {
            Logger.i("用户点击账号登录按钮执行登录功能,real登录");
            GTConfig.instance().setAccountType(GTConfig.ACC_TYPE_REAL);
            MobclickAgent.onProfileSignIn("Real_Login", mCurName);
            MobclickEventUtlis.MobclickEvent(this, "Real_Login");
            executeLogin(mCurName, mPassword);
        }

    }

    /**
     * 执行登录逻辑
     */
    private void executeLogin(String loginName, String loginPassWord) {
        mPresenter.mCurName = loginName;
        mPresenter.mPassword = loginPassWord;
        mPresenter.isLoading = true;
        mPresenter.isClickLogin = true;
        mPresenter.setPresenterImpl(this);
        DataManager.instance().reset();
//        AppActivities.getSingleton().popAllActivityExceptOne(PasswordCheckActivity.this.getClass().getSimpleName());
        mPresenter.loginFun();
    }


    /**
     * 处理异常连接失败(比如登录超时、行情连接失败、交易连接失败等)
     *
     * @param errorShowMsg 提示的错误信息
     */
    private void dealException(String errorShowMsg) {
        PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(this, "", errorShowMsg);
        dialog.setCancelable(false);
        dialog.show();
    }

    /**
     * 当验证密码成功
     */
    @Override
    public void onRequestSuc(Object result) {
        Log.d("onRequestTag", "Suc");
        hideLoading();
        new ToastPopWindow(this, "验证成功").show();
        ActivityManager.dispatchGesture("dispatchGestureTag1:byUser", this, GesturePwdConst.MODE_RESET);//结束自己，并且进入 GesturePwdResetActivity
        finish();
    }

    /**
     * 当验证密码失败
     */
    @Override
    public void onRequestFail(int failCode) {
        Log.d("onRequestTag", "FailCode:" + failCode);
//        new ToastPopWindow(this, "登录密码不正确，请重新输入").show();
        //这里会被JNI调用GTSDataListener.java 283行的弹出框覆盖；所以算了吧，这里改不了
    }

    @Override
    public void finish() {
        super.finish();
        AppTerminal.instance().setLoginView(0);
        if (null != mPresenter) {
            mPresenter.setPresenterImpl(null);
            mPresenter.clear();
        }
    }

}
